Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,

If nums = [1,2,2], a solution is:

  1. [
  2. [2],
  3. [1],
  4. [1,2,2],
  5. [2,2],
  6. [1,2],
  7. []
  8. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> subsetsWithDup(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. res.add(new ArrayList<Integer>());
  5. Arrays.sort(nums);
  6. int lastSize = 0;
  7. for (int i = 0; i < nums.length; i++) {
  8. int size = res.size();
  9. int start = (i == 0 || nums[i] != nums[i - 1]) ? 0 : lastSize;
  10. for (int j = start; j < size; j++) {
  11. List<Integer> sol = new ArrayList<Integer>(res.get(j));
  12. sol.add(nums[i]);
  13. res.add(sol);
  14. }
  15. lastSize = size;
  16. }
  17. return res;
  18. }
  19. }